package com.example.oss.service.serviceImpl;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.UUID;

import org.joda.time.DateTime;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.example.oss.service.FileService;
import com.example.oss.utils.ConstantPropertiesUtil;
@Service
public class FileServiceImpl implements FileService{

	@Override
	public String fileUpload(MultipartFile file) {
		// TODO Auto-generated method stub
		
		// Endpoint以杭州为例，其它Region请按实际情况填写。
		
		String endpoint = ConstantPropertiesUtil.END_POINT;
		// 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。
		String accessKeyId = ConstantPropertiesUtil.KEY_ID;
		String accessKeySecret = ConstantPropertiesUtil.KEY_SECRET;
		String accessBucketName = ConstantPropertiesUtil.BUCKET_NAME;
        String fileName = file.getOriginalFilename();
		// 创建OSSClient实例。
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
		String uploadUri = null;
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		fileName = uuid +fileName;
		String datePath = new DateTime().toString("yyyy/MM/dd");
		fileName = datePath+"/"+fileName;
		// 上传文件流。
		try {
//			InputStream inputStream = new FileInputStream(file.getClass());
			InputStream inputStream = file.getInputStream();
			ossClient.putObject(accessBucketName, fileName, inputStream);
			ossClient.shutdown();

//https://heartlight.oss-cn-beijing.aliyuncs.com/142.jpg
			uploadUri = "https://"+accessBucketName+"."+endpoint+"/"+fileName+"";
			System.out.println(uploadUri);
			return uploadUri;
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		return uploadUri;
		

		// 关闭OSSClient。
		
	}

}
